const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
// 引入插件
const ExtractTextPlugin = require('extract-text-webpack-plugin'); //css单独打包
const HtmlWebpackPlugin = require('html-webpack-plugin'); //生成html
const CleanWebpackPlugin = require('clean-webpack-plugin');//清空发布文件夹；
//定义地址
const ROOT_PATH = path.resolve(__dirname);
const APP_PATH = path.resolve(ROOT_PATH, 'src'); //__dirname 中的src目录，以此类推
const BUILD_PATH = path.resolve(ROOT_PATH, 'dist'); //发布文件所存放的目录
const PUBLIC_PATH = '/';

const getEntry = (globPath, pathDir) => {
    let files = glob.sync(globPath);
    let entries = {}, entry, dirname, basename, pathname, extname;
    for (let i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);
        extname = path.extname(entry);
        basename = path.basename(entry, extname);
        pathname = path.normalize(path.join(dirname, basename));
        pathDir = path.normalize(pathDir);
        if (pathname.startsWith(pathDir)) {
            pathname = pathname.substring(pathDir.length)
        }
        entries[pathname] = ['./' + entry];
    }
    return entries;
};
const entries = getEntry('src/js/page/**/*.js', 'src/js/page/');
const chunks = Object.keys(entries);

const config = {
    entry: entries,
    output: {
        path: BUILD_PATH,                   //输出目录的配置，模板、样式、脚本、图片等资源的路径配置都相对于它
        publicPath: PUBLIC_PATH,			//模板、样式、脚本、图片等资源对应的server上的路径
        filename: 'js/[name].js',			//每个页面对应的主js的生成配置
        chunkFilename: 'js/[id].chunk.js'   //chunk生成的配置
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /^node_modules$/,
            loader: 'babel',
            include: [APP_PATH]
        }, {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract('style', ['css', 'postcss'])
        }, {
            test: /\.less$/,
            exclude: /^node_modules$/,
            loader: ExtractTextPlugin.extract('style', ['css', 'postcss', 'less'])
        }, {
            test: /\.scss$/,
            exclude: /^node_modules$/,
            loader: ExtractTextPlugin.extract('style', ['css', 'postcss', 'sass'])
        }, {
            //html模板加载器，可以处理引用的静态资源，默认配置参数attrs=img:src，处理图片的src引用的资源
            test: /\.html$/,
            loader: "html?-minimize&interpolate=require"
        }, {
            test: /\.(eot|woff|svg|ttf|woff2|gif|appcache)(\?|$)/,
            loader: 'file-loader?name=img/[name].[ext]'
        }, {
            test: /\.(png|jpg|gif)$/,
            loader: 'url-loader?limit=8192&name=img/[hash:5].[name].[ext]',
        }]
    },
    externals: {
        jquery: 'window.$'
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production') //定义生产环境
            }
        }),
        //清空发布文件夹；
        new CleanWebpackPlugin(BUILD_PATH),
        //单独打包后输出路径及名称；
        new ExtractTextPlugin('css/[name].css'),
        //热加载,
        new webpack.HotModuleReplacementPlugin(),
        // 将公共模块提取
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendors', //生成名为`vendors`的chunk
            chunks: chunks,
            minChunks: chunks.length // 提取所有entry共同依赖的模块
        }),
        // js压缩；由于用到html-webpack-plugin；css及HTML都会打包；
        new webpack.optimize.UglifyJsPlugin({
            output: {
                comments: false, // remove all comments
            },
            compress: {
                warnings: false,
                drop_console: true
            }
        })
    ],
    resolve: {
        //后缀名自动补全
        extensions: ['', '.js', '.jsx', '.less', '.scss', '.css'],
        // 自定义路径别名
        alias: {
            IMG: path.join(APP_PATH, 'img'),
            STYLE: path.join(APP_PATH, 'css'),
            LIB: path.join(APP_PATH, 'lib'),
            COMPONENT: path.join(APP_PATH, 'js/components'),
            UTIL: path.join(APP_PATH, 'js/utils')
        }
    }
};
const pages = Object.keys(getEntry('src/view/**/*.html', 'src/view/'));
pages.forEach(function (pathname) {
    let conf = {
        filename: pathname + '.html', //生成的html存放路径，相对于path
        template: 'src/view/' + pathname + '.html', //html模板路径
        inject: false, //js插入的位置，true/'head'/'body'/false
        /*
         * 压缩这块，调用了html-minify，会导致压缩时候的很多html语法检查问题，
         * 如在html标签属性上使用{{...}}表达式，很多情况下并不需要在此配置压缩项，
         * 另外，UglifyJsPlugin会在压缩代码的时候连同html一起压缩。
         * 为避免压缩html，需要在html-loader上配置'html?-minimize'，见loaders中html-loader的配置。
         */
        minify: { //压缩HTML文件
            removeComments: true, //移除HTML中的注释
            collapseWhitespace: false //删除空白符与换行符
        }
    };
    if (pathname in config.entry) {
        // conf.favicon = path.resolve(__dirname, 'src/imgs/favicon.ico');
        conf.inject = 'body';
        conf.chunks = ['vendors', pathname];
        conf.hash = true;
    }
    config.plugins.push(new HtmlWebpackPlugin(conf));
});

module.exports = config;